<?php
class ControllerApiOrder extends Controller {
	public function add() {
		$this->load->language('api/order');

		$json = array();

		if (!isset($this->session->data['api_id'])) {
			$json['error'] = $this->language->get('error_permission');
		} else {
			// Customer
			if (!isset($this->session->data['customer'])) {
				$json['error'] = $this->language->get('error_customer');
			}

			// Payment Address
			if (!isset($this->session->data['payment_address'])) {
				$json['error'] = $this->language->get('error_payment_address');
			}

			// Payment Method
			if (!$json && !empty($this->request->post['payment_method'])) {
				if (empty($this->session->data['payment_methods'])) {
					$json['error'] = $this->language->get('error_no_payment');
				} elseif (!isset($this->session->data['payment_methods'][$this->request->post['payment_method']])) {
					$json['error'] = $this->language->get('error_payment_method');
				}

				if (!$json) {
					$this->session->data['payment_method'] = $this->session->data['payment_methods'][$this->request->post['payment_method']];
				}
			}

			if (!isset($this->session->data['payment_method'])) {
				$json['error'] = $this->language->get('error_payment_method');
			}

			// Shipping
			if ($this->cart->hasShipping()) {
				// Shipping Address
				if (!isset($this->session->data['shipping_address'])) {
					$json['error'] = $this->language->get('error_shipping_address');
				}

				// Shipping Method
				if (!$json && !empty($this->request->post['shipping_method'])) {
					if (empty($this->session->data['shipping_methods'])) {
						$json['error'] = $this->language->get('error_no_shipping');
					} else {
						$shipping = explode('.', $this->request->post['shipping_method']);

						if (!isset($shipping[0]) || !isset($shipping[1]) || !isset($this->session->data['shipping_methods'][$shipping[0]]['quote'][$shipping[1]])) {
							$json['error'] = $this->language->get('error_shipping_method');
						}
					}

					if (!$json) {
						$this->session->data['shipping_method'] = $this->session->data['shipping_methods'][$shipping[0]]['quote'][$shipping[1]];
					}
				}

				// Shipping Method
				if (!isset($this->session->data['shipping_method'])) {
					$json['error'] = $this->language->get('error_shipping_method');
				}
			} else {
				unset($this->session->data['shipping_address']);
				unset($this->session->data['shipping_method']);
				unset($this->session->data['shipping_methods']);
			}

			// Cart
			if ((!$this->cart->hasProducts() && empty($this->session->data['vouchers'])) || (!$this->cart->hasStock() && !$this->config->get('config_stock_checkout'))) {
				$json['error'] = $this->language->get('error_stock');
			}

			// Validate minimum quantity requirements.
			$products = $this->cart->getProducts();

			foreach ($products as $product) {
				$product_total = 0;

				foreach ($products as $product_2) {
					if ($product_2['product_id'] == $product['product_id']) {
						$product_total += $product_2['quantity'];
					}
				}

				// if ($product['minimum'] > $product_total) {
				// 	$json['error'] = sprintf($this->language->get('error_minimum'), $product['name'], $product['minimum']);

				// 	break;
				// }
			}

			if (!$json) {
				$order_data = array();

				// Store Details
				$order_data['invoice_prefix'] = $this->config->get('config_invoice_prefix');
				$order_data['store_id'] = $this->config->get('config_store_id');
				$order_data['store_name'] = $this->config->get('config_name');
				$order_data['store_url'] = $this->config->get('config_url');

				// Customer Details
				$order_data['customer_id'] = $this->session->data['customer']['customer_id'];
				$order_data['customer_group_id'] = $this->session->data['customer']['customer_group_id'];
				$order_data['fullname'] = $this->session->data['customer']['fullname'];
				$order_data['email'] = $this->session->data['customer']['email'];
				$order_data['telephone'] = $this->session->data['customer']['telephone'];
				$order_data['fax'] = $this->session->data['customer']['fax'];
				$order_data['custom_field'] = $this->session->data['customer']['custom_field'];

				// Payment Details
				$order_data['payment_fullname'] = $this->session->data['payment_address']['fullname'];
				$order_data['payment_company'] = $this->session->data['payment_address']['company'];
				$order_data['payment_address'] = $this->session->data['payment_address']['address'];
				$order_data['payment_city'] = $this->session->data['payment_address']['city'];
				$order_data['payment_city_id'] = $this->session->data['payment_address']['city_id'];
				$order_data['payment_postcode'] = $this->session->data['payment_address']['postcode'];
				$order_data['payment_zone'] = $this->session->data['payment_address']['zone'];
				$order_data['payment_zone_id'] = $this->session->data['payment_address']['zone_id'];
				$order_data['payment_country'] = $this->session->data['payment_address']['country'];
				$order_data['payment_country_id'] = $this->session->data['payment_address']['country_id'];
				$order_data['payment_address_format'] = $this->session->data['payment_address']['address_format'];
				$order_data['payment_custom_field'] = (isset($this->session->data['payment_address']['custom_field']) ? $this->session->data['payment_address']['custom_field'] : array());

				if (isset($this->session->data['payment_method']['title'])) {
					$order_data['payment_method'] = $this->session->data['payment_method']['title'];
				} else {
					$order_data['payment_method'] = '';
				}

				if (isset($this->session->data['payment_method']['code'])) {
					$order_data['payment_code'] = $this->session->data['payment_method']['code'];
				} else {
					$order_data['payment_code'] = '';
				}

				// Shipping Details
				if ($this->cart->hasShipping()) {
					$order_data['shipping_fullname'] = $this->session->data['shipping_address']['fullname'];
					$order_data['shipping_company'] = $this->session->data['shipping_address']['company'];
					$order_data['shipping_address'] = $this->session->data['shipping_address']['address'];
					$order_data['shipping_telephone'] = $this->session->data['shipping_address']['shipping_telephone'];
					$order_data['shipping_city'] = $this->session->data['shipping_address']['city'];
					$order_data['shipping_city_id'] = $this->session->data['shipping_address']['city_id'];
					$order_data['shipping_postcode'] = $this->session->data['shipping_address']['postcode'];
					$order_data['shipping_zone'] = $this->session->data['shipping_address']['zone'];
					$order_data['shipping_zone_id'] = $this->session->data['shipping_address']['zone_id'];
					$order_data['shipping_country'] = $this->session->data['shipping_address']['country'];
					$order_data['shipping_country_id'] = $this->session->data['shipping_address']['country_id'];
					$order_data['shipping_address_format'] = $this->session->data['shipping_address']['address_format'];
					$order_data['shipping_custom_field'] = (isset($this->session->data['shipping_address']['custom_field']) ? $this->session->data['shipping_address']['custom_field'] : array());

					if (isset($this->session->data['shipping_method']['title'])) {
						$order_data['shipping_method'] = $this->session->data['shipping_method']['title'];
					} else {
						$order_data['shipping_method'] = '';
					}

					if (isset($this->session->data['shipping_method']['code'])) {
						$order_data['shipping_code'] = $this->session->data['shipping_method']['code'];
					} else {
						$order_data['shipping_code'] = '';
					}
				} else {
					$order_data['shipping_fullname'] = '';
					$order_data['shipping_company'] = '';
					$order_data['shipping_address'] = '';
					$order_data['shipping_city'] = '';
					$order_data['shipping_city_id'] = '';
					$order_data['shipping_telephone'] = '';
					$order_data['shipping_postcode'] = '';
					$order_data['shipping_zone'] = '';
					$order_data['shipping_zone_id'] = '';
					$order_data['shipping_country'] = '';
					$order_data['shipping_country_id'] = '';
					$order_data['shipping_address_format'] = '';
					$order_data['shipping_custom_field'] = array();
					$order_data['shipping_method'] = '';
					$order_data['shipping_code'] = '';
				}

				// Gift Voucher
				$order_data['vouchers'] = array();

				if (!empty($this->session->data['vouchers'])) {
					foreach ($this->session->data['vouchers'] as $voucher) {
						$order_data['vouchers'][] = array(
							'description'      => $voucher['description'],
							'code'             => substr(token(32), 0, 10),
							'to_name'          => $voucher['to_name'],
							'to_email'         => $voucher['to_email'],
							'from_name'        => $voucher['from_name'],
							'from_email'       => $voucher['from_email'],
							'voucher_theme_id' => $voucher['voucher_theme_id'],
							'message'          => $voucher['message'],
							'amount'           => $voucher['amount']
						);
					}
				}

				// Order Totals
				$this->load->model('extension/extension');

				$order_data['totals'] = array();
				$total = 0;
				$taxes = $this->cart->getTaxes();

				$sort_order = array();

				$results = $this->model_extension_extension->getExtensions('total');

				foreach ($results as $key => $value) {
					$sort_order[$key] = $this->config->get($value['code'] . '_sort_order');
				}

				array_multisort($sort_order, SORT_ASC, $results);

				foreach ($results as $result) {
					if ($this->config->get($result['code'] . '_status')) {
						$this->load->model('total/' . $result['code']);

						if($result['code'] != 'favour')
							$this->{'model_total_' . $result['code']}->getTotal($order_data['totals'], $total, $taxes);
						else
							$this->model_total_favour->getTotal($order_data['totals'], $total, $taxes, $post['payment_code']=='cod' || $post['payment_code']=='magfin'?true:false);
					}
				}

				$sort_order = array();

				foreach ($order_data['totals'] as $key => $value) {
					$sort_order[$key] = $value['sort_order'];
				}

				array_multisort($sort_order, SORT_ASC, $order_data['totals']);

				if (isset($this->request->post['comment'])) {
					$order_data['comment'] = $this->request->post['comment'];
				} else {
					$order_data['comment'] = '';
				}

				$order_data['total'] = $total;

				// Products
				$order_data['products'] = array();

				$spreadratio = $total/$this->cart->getSubTotal();

				foreach ($this->cart->getProducts() as $product) {
					$option_data = array();

					foreach ($product['option'] as $option) {
						$option_data[] = array(
							'product_option_id'       => $option['product_option_id'],
							'product_option_value_id' => $option['product_option_value_id'],
							'option_id'               => $option['option_id'],
							'option_value_id'         => $option['option_value_id'],
							'name'                    => $option['name'],
							'value'                   => $option['value'],
							'type'                    => $option['type']
						);
					}

					$order_data['products'][] = array(
						'product_id' => $product['product_id'],
						'name'       => $product['name'],
						'model'      => $product['model'],
						'option'     => $option_data,
						'download'   => $product['download'],
						'quantity'   => $product['quantity'],
						'subtract'   => $product['subtract'],
						'price'      => $product['price'],
						'pay_price'  => round($product['price']*$spreadratio,2),
						'total'      => $product['total'],
						'pay_total'  => round($product['total']*$spreadratio,2),
						'tax'        => $this->tax->getTax($product['price'], $product['tax_class_id']),
						'reward'     => $product['reward']
					);
				}

				if (isset($this->request->post['affiliate_id'])) {
					$subtotal = $this->cart->getSubTotal();

					// Affiliate
					$this->load->model('affiliate/affiliate');

					$affiliate_info = $this->model_affiliate_affiliate->getAffiliate($this->request->post['affiliate_id']);

					if ($affiliate_info) {
						$order_data['affiliate_id'] = $affiliate_info['affiliate_id'];
						$order_data['commission'] = ($subtotal / 100) * $affiliate_info['commission'];
					} else {
						$order_data['affiliate_id'] = 0;
						$order_data['commission'] = 0;
					}

					// Marketing
					$order_data['marketing_id'] = 0;
					$order_data['tracking'] = '';
				} else {
					$order_data['affiliate_id'] = 0;
					$order_data['commission'] = 0;
					$order_data['marketing_id'] = 0;
					$order_data['tracking'] = '';
				}

				$order_data['language_id'] = $this->config->get('config_language_id');
				$order_data['currency_id'] = $this->currency->getId();
				$order_data['currency_code'] = $this->currency->getCode();
				$order_data['currency_value'] = $this->currency->getValue($this->currency->getCode());
				$order_data['ip'] = $this->request->server['REMOTE_ADDR'];

				if (!empty($this->request->server['HTTP_X_FORWARDED_FOR'])) {
					$order_data['forwarded_ip'] = $this->request->server['HTTP_X_FORWARDED_FOR'];
				} elseif (!empty($this->request->server['HTTP_CLIENT_IP'])) {
					$order_data['forwarded_ip'] = $this->request->server['HTTP_CLIENT_IP'];
				} else {
					$order_data['forwarded_ip'] = '';
				}

				if (isset($this->request->server['HTTP_USER_AGENT'])) {
					$order_data['user_agent'] = $this->request->server['HTTP_USER_AGENT'];
				} else {
					$order_data['user_agent'] = '';
				}

				if (isset($this->request->server['HTTP_ACCEPT_LANGUAGE'])) {
					$order_data['accept_language'] = $this->request->server['HTTP_ACCEPT_LANGUAGE'];
				} else {
					$order_data['accept_language'] = '';
				}

				$order_data['logcenter_id'] = $this->customer->getLogcenterId();

				$this->load->model('checkout/order');

				$json['order_id'] = $this->model_checkout_order->addOrder($order_data);
				//添加应付
				$res= $this->model_checkout_order->getMoneyOrder($json['order_id']);
				$this->model_checkout_order->addMoneyOrder($res);
				if ($res['is_pay']==1) {
					$this->model_checkout_order->updatemoney($res['totalp'],$order_id);
				}
				// Set the order history
				// if (isset($this->request->post['order_status_id'])) {
				// 	$order_status_id = $this->request->post['order_status_id'];
				// } else {
				// 	$order_status_id = $this->config->get('config_order_status_id');
				// }


				if($order_data['payment_code'] == 'cod'){
					$order_status_id = 2;
				}else{
					$order_status_id = 1;
				}
				//物流营销中心新建订单状态为待审核
				if(isset($this->request->get['is_lgi'])&&$this->request->get['is_lgi']==1) {
					if (isset($this->request->post['order_status_id'])) {
						$order_status_id = $this->request->post['order_status_id'];
					} else {
						$order_status_id = $this->config->get('config_order_status_id');
					}
				} 

				$this->model_checkout_order->addOrderHistory($json['order_id'], $order_status_id);

				$json['success'] = $this->language->get('text_success');
			}
		}

		if (isset($this->request->server['HTTP_ORIGIN'])) {
			$this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
			$this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
			$this->response->addHeader('Access-Control-Max-Age: 1000');
			$this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

	public function edit() {
		$this->load->language('api/order');

		$json = array();

		if (!isset($this->session->data['api_id'])) {
			$json['error'] = $this->language->get('error_permission');
		} else {
			$this->load->model('checkout/order');

			if (isset($this->request->get['order_id'])) {
				$order_id = $this->request->get['order_id'];
			} else {
				$order_id = 0;
			}

			$order_info = $this->model_checkout_order->getOrder($order_id);

			if ($order_info) {
				// Customer
				if (!isset($this->session->data['customer'])) {
					$json['error'] = $this->language->get('error_customer');
				}

				// Payment Address
				if (!isset($this->session->data['payment_address'])) {
					$json['error'] = $this->language->get('error_payment_address');
				}

				// Payment Method
				if (!$json && !empty($this->request->post['payment_method'])) {
					if (empty($this->session->data['payment_methods'])) {
						$json['error'] = $this->language->get('error_no_payment');
					} elseif (!isset($this->session->data['payment_methods'][$this->request->post['payment_method']])) {
						$json['error'] = $this->language->get('error_payment_method');
					}

					if (!$json) {
						$this->session->data['payment_method'] = $this->session->data['payment_methods'][$this->request->post['payment_method']];
					}
				}

				if (!isset($this->session->data['payment_method'])) {
					$json['error'] = $this->language->get('error_payment_method');
				}

				// Shipping
				if ($this->cart->hasShipping()) {
					// Shipping Address
					if (!isset($this->session->data['shipping_address'])) {
						$json['error'] = $this->language->get('error_shipping_address');
					}

					// Shipping Method
					if (!$json && !empty($this->request->post['shipping_method'])) {
						if (empty($this->session->data['shipping_methods'])) {
							$json['error'] = $this->language->get('error_no_shipping');
						} else {
							$shipping = explode('.', $this->request->post['shipping_method']);

							if (!isset($shipping[0]) || !isset($shipping[1]) || !isset($this->session->data['shipping_methods'][$shipping[0]]['quote'][$shipping[1]])) {
								$json['error'] = $this->language->get('error_shipping_method');
							}
						}

						if (!$json) {
							$this->session->data['shipping_method'] = $this->session->data['shipping_methods'][$shipping[0]]['quote'][$shipping[1]];
						}
					}

					if (!isset($this->session->data['shipping_method'])) {
						$json['error'] = $this->language->get('error_shipping_method');
					}
				} else {
					unset($this->session->data['shipping_address']);
					unset($this->session->data['shipping_method']);
					unset($this->session->data['shipping_methods']);
				}

				// Cart
				if ((!$this->cart->hasProducts() && empty($this->session->data['vouchers'])) || (!$this->cart->hasStock() && !$this->config->get('config_stock_checkout'))) {
					$json['error'] = $this->language->get('error_stock');
				}

				// Validate minimum quantity requirements.
				$products = $this->cart->getProducts();

				foreach ($products as $product) {
					$product_total = 0;

					foreach ($products as $product_2) {
						if ($product_2['product_id'] == $product['product_id']) {
							$product_total += $product_2['quantity'];
						}
					}

					if ($product['minimum'] > $product_total) {
						$json['error'] = sprintf($this->language->get('error_minimum'), $product['name'], $product['minimum']);

						break;
					}
				}

				if (!$json) {
					$order_data = array();

					// Store Details
					$order_data['invoice_prefix'] = $this->config->get('config_invoice_prefix');
					$order_data['store_id'] = $this->config->get('config_store_id');
					$order_data['store_name'] = $this->config->get('config_name');
					$order_data['store_url'] = $this->config->get('config_url');

					// Customer Details
					$order_data['customer_id'] = $this->session->data['customer']['customer_id'];
					$order_data['customer_group_id'] = $this->session->data['customer']['customer_group_id'];
					$order_data['fullname'] = $this->session->data['customer']['fullname'];
					$order_data['email'] = $this->session->data['customer']['email'];
					$order_data['telephone'] = $this->session->data['customer']['telephone'];
					$order_data['fax'] = $this->session->data['customer']['fax'];
					$order_data['custom_field'] = $this->session->data['customer']['custom_field'];

					// Payment Details
					$order_data['payment_fullname'] = $this->session->data['payment_address']['fullname'];
					$order_data['payment_company'] = $this->session->data['payment_address']['company'];
					$order_data['payment_address'] = $this->session->data['payment_address']['address'];
					$order_data['payment_city'] = $this->session->data['payment_address']['city'];
					$order_data['payment_city_id'] = $this->session->data['payment_address']['city_id'];
					$order_data['payment_postcode'] = $this->session->data['payment_address']['postcode'];
					$order_data['payment_zone'] = $this->session->data['payment_address']['zone'];
					$order_data['payment_zone_id'] = $this->session->data['payment_address']['zone_id'];
					$order_data['payment_country'] = $this->session->data['payment_address']['country'];
					$order_data['payment_country_id'] = $this->session->data['payment_address']['country_id'];
					$order_data['payment_address_format'] = $this->session->data['payment_address']['address_format'];
					$order_data['payment_custom_field'] = $this->session->data['payment_address']['custom_field'];

					if (isset($this->session->data['payment_method']['title'])) {
						$order_data['payment_method'] = $this->session->data['payment_method']['title'];
					} else {
						$order_data['payment_method'] = '';
					}

					if (isset($this->session->data['payment_method']['code'])) {
						$order_data['payment_code'] = $this->session->data['payment_method']['code'];
					} else {
						$order_data['payment_code'] = '';
					}

					// Shipping Details
					if ($this->cart->hasShipping()) {
						$order_data['shipping_fullname'] = $this->session->data['shipping_address']['fullname'];
						$order_data['shipping_company'] = $this->session->data['shipping_address']['company'];
						$order_data['shipping_address'] = $this->session->data['shipping_address']['address'];
						$order_data['shipping_telephone'] = $this->session->data['shipping_address']['shipping_telephone'];
						$order_data['shipping_city'] = $this->session->data['shipping_address']['city'];
						$order_data['shipping_city_id'] = $this->session->data['shipping_address']['city_id'];
						$order_data['shipping_postcode'] = $this->session->data['shipping_address']['postcode'];
						$order_data['shipping_zone'] = $this->session->data['shipping_address']['zone'];
						$order_data['shipping_zone_id'] = $this->session->data['shipping_address']['zone_id'];
						$order_data['shipping_country'] = $this->session->data['shipping_address']['country'];
						$order_data['shipping_country_id'] = $this->session->data['shipping_address']['country_id'];
						$order_data['shipping_address_format'] = $this->session->data['shipping_address']['address_format'];
						$order_data['shipping_custom_field'] = $this->session->data['shipping_address']['custom_field'];

						if (isset($this->session->data['shipping_method']['title'])) {
							$order_data['shipping_method'] = $this->session->data['shipping_method']['title'];
						} else {
							$order_data['shipping_method'] = '';
						}

						if (isset($this->session->data['shipping_method']['code'])) {
							$order_data['shipping_code'] = $this->session->data['shipping_method']['code'];
						} else {
							$order_data['shipping_code'] = '';
						}
					} else {
						$order_data['shipping_fullname'] = '';
						$order_data['shipping_company'] = '';
						$order_data['shipping_address'] = '';
						$order_data['shipping_city'] = '';
						$order_data['shipping_city_id'] = '';
						$order_data['shipping_telephone'] = '';
						$order_data['shipping_postcode'] = '';
						$order_data['shipping_zone'] = '';
						$order_data['shipping_zone_id'] = '';
						$order_data['shipping_country'] = '';
						$order_data['shipping_country_id'] = '';
						$order_data['shipping_address_format'] = '';
						$order_data['shipping_custom_field'] = array();
						$order_data['shipping_method'] = '';
						$order_data['shipping_code'] = '';
					}

					// Products
					$order_data['products'] = array();

					foreach ($this->cart->getProducts() as $product) {
						$option_data = array();

						foreach ($product['option'] as $option) {
							$option_data[] = array(
								'product_option_id'       => $option['product_option_id'],
								'product_option_value_id' => $option['product_option_value_id'],
								'option_id'               => $option['option_id'],
								'option_value_id'         => $option['option_value_id'],
								'name'                    => $option['name'],
								'value'                   => $option['value'],
								'type'                    => $option['type']
							);
						}

						$order_data['products'][] = array(
							'product_id' => $product['product_id'],
							'name'       => $product['name'],
							'model'      => $product['model'],
							'option'     => $option_data,
							'download'   => $product['download'],
							'quantity'   => $product['quantity'],
							'subtract'   => $product['subtract'],
							'price'      => $product['price'],
							'total'      => $product['total'],
							'tax'        => $this->tax->getTax($product['price'], $product['tax_class_id']),
							'reward'     => $product['reward']
						);
					}

					// Gift Voucher
					$order_data['vouchers'] = array();

					if (!empty($this->session->data['vouchers'])) {
						foreach ($this->session->data['vouchers'] as $voucher) {
							$order_data['vouchers'][] = array(
								'description'      => $voucher['description'],
								'code'             => token(10),
								'to_name'          => $voucher['to_name'],
								'to_email'         => $voucher['to_email'],
								'from_name'        => $voucher['from_name'],
								'from_email'       => $voucher['from_email'],
								'voucher_theme_id' => $voucher['voucher_theme_id'],
								'message'          => $voucher['message'],
								'amount'           => $voucher['amount']
							);
						}
					}

					// Order Totals
					$this->load->model('extension/extension');

					$order_data['totals'] = array();
					$total = 0;
					$taxes = $this->cart->getTaxes();

					$sort_order = array();

					$results = $this->model_extension_extension->getExtensions('total');

					foreach ($results as $key => $value) {
						$sort_order[$key] = $this->config->get($value['code'] . '_sort_order');
					}

					array_multisort($sort_order, SORT_ASC, $results);

					foreach ($results as $result) {
						if ($this->config->get($result['code'] . '_status')) {
							$this->load->model('total/' . $result['code']);

							$this->{'model_total_' . $result['code']}->getTotal($order_data['totals'], $total, $taxes);
						}
					}

					$sort_order = array();

					foreach ($order_data['totals'] as $key => $value) {
						$sort_order[$key] = $value['sort_order'];
					}

					array_multisort($sort_order, SORT_ASC, $order_data['totals']);

					if (isset($this->request->post['comment'])) {
						$order_data['comment'] = $this->request->post['comment'];
					} else {
						$order_data['comment'] = '';
					}

					$order_data['total'] = $total;

					if (isset($this->request->post['affiliate_id'])) {
						$subtotal = $this->cart->getSubTotal();

						// Affiliate
						$this->load->model('affiliate/affiliate');

						$affiliate_info = $this->model_affiliate_affiliate->getAffiliate($this->request->post['affiliate_id']);

						if ($affiliate_info) {
							$order_data['affiliate_id'] = $affiliate_info['affiliate_id'];
							$order_data['commission'] = ($subtotal / 100) * $affiliate_info['commission'];
						} else {
							$order_data['affiliate_id'] = 0;
							$order_data['commission'] = 0;
						}
					} else {
						$order_data['affiliate_id'] = 0;
						$order_data['commission'] = 0;
					}

					$this->model_checkout_order->editOrder($order_id, $order_data);

					// Set the order history
					if (isset($this->request->post['order_status_id'])) {
						$order_status_id = $this->request->post['order_status_id'];
					} else {
						$order_status_id = $this->config->get('config_order_status_id');
					}

					$this->model_checkout_order->addOrderHistory($order_id, $order_status_id);

					$json['success'] = $this->language->get('text_success');
				}
			} else {
				$json['error'] = $this->language->get('error_not_found');
			}
		}

		if (isset($this->request->server['HTTP_ORIGIN'])) {
			$this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
			$this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
			$this->response->addHeader('Access-Control-Max-Age: 1000');
			$this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

	public function delete() {
		$this->load->language('api/order');


		$json = array();

		if (!isset($this->session->data['api_id'])) {
			$json['error'] = $this->language->get('error_permission');
		} else {
			$this->load->model('checkout/order');

			if (isset($this->request->get['order_id'])) {
				$order_id = $this->request->get['order_id'];
			} else {
				$order_id = 0;
			}
			$stock_info = $this->model_checkout_order->getStock($order_id);
			if (empty($stock_info['out_id'])) {
				$order_info = $this->model_checkout_order->getOrder($order_id);

				if ($order_info) {
					$this->model_checkout_order->addorderHistory($order_id,16,'无效订单');
					$money = $this->model_checkout_order->getMoneyById($order_id);
					if ($money) {
						$this->model_checkout_order->updateMoneystatus($order_id);
					}
					$json['success'] = $this->language->get('text_success');
				} else {
					$json['error'] = $this->language->get('error_not_found');
				}
			}else{
				$json['error'] = "出库单已经生成，订单不能删除";

			}

			
		}

		if (isset($this->request->server['HTTP_ORIGIN'])) {
			$this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
			$this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
			$this->response->addHeader('Access-Control-Max-Age: 1000');
			$this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
		}
		// var_dump($json);die();

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

    /* 订单审核配货v2 开始 */
    /*
     * 订单审核配货
     * 配货顺序
     * 根据订单号，找到所属的物流中心
     * 1. 根据订单所属的物流中心，找到本地发货仓，作为第一顺位配货仓
     * 2. 根据订单所属的物流中心，找到大区内总仓，作为第二顺位配货仓（暂时只有华东一个大区）
     * 3. 获取大区内所有包含全区域配送商品清单的分仓，根据区域分仓和订单归属物流中心的距离（经纬度计算得出），确定分仓配货顺位后进行配货（距离越近顺位越高）
     * @author sonicsjh
     */
    public function verify_v2() {
        $this->load->language('api/order');
        $this->load->model('checkout/order');
        $ret = array();
        if ($this->session->data['api_id']) {
            $orderId = intval($this->request->get['order_id']);
            $soForce = ('anyway' == $this->request->get['how'])?true:false;
            $userId = intval($this->request->get['user_id']);//操作人编号
            $orderInfo = $this->model_checkout_order->getOrder($orderId);
            if ($orderId == $orderInfo['order_id']) {
            	//检验要审核的状态
                $canVerify = $this->_canVerify($orderInfo);
                if (true === $canVerify) {
                    $warehouseList = $this->_getWarehouseListByLogcenter($orderInfo['warehouse_id']);//warehouse_id为c表的logcenter_id @todo@ 隐患，拆分logcenter和warehouse的时候修正
                    $SOInfo = $this->_inventoryCheck($orderId, $userId, $warehouseList, $soForce);//循环配货
                    $OTList = $this->model_checkout_order->getOTList($orderId);//获取订单total表信息列表
                    foreach ($OTList as $OTInfo) {
                        if ('sub_total' == $OTInfo['code']) {
                            $orderSubTotal = $OTInfo['value'];//获取订单商品汇总价格
                        }else if ($OTInfo['value'] < 0) {
                            $OTLtZero[] = $OTInfo;
                        }
                    }
                    if (count($SOInfo['qtyToSO']) < 1) {
                        $canSORate = 100;//避免因商品组的价格误差导致的99%出库，实际订单全部出库
                    }else{
                        $canSORate = min(100, floor($SOInfo['soTotalPrice']/$orderSubTotal*100));//可出库比例
                    }
                    if ($SOInfo['isSO']) {//创建出库单后额外操作
                        foreach ($OTLtZero as $OTInfo) {
                            $this->model_checkout_stock_out->insertOTIntoSO($orderId, $OTInfo['order_total_id'], $OTInfo['value']);
                        }
                        $this->model_checkout_order->resetSORate_v2($orderId, $canSORate);//每次出库，更新实际出库比例
                        /* @todo@ 待优化，addorderHistory 方法进行了很多操作，需要完整梳理订单状态后优化 */
                        if (100 == $canSORate) {
                            $this->model_checkout_order->addorderHistory($orderId, 2, '审核通过');
                            $this->model_checkout_order->updateorderverify($orderId, 2);//更新订单审核状态
                        }else{
                            $this->model_checkout_order->updateorderverify($orderId, 1);//更新订单审核状态
                        }
                        //$orderStatusId = (100 == $canSORate)?2:17;//判断是否全部发货
                        //$this->model_checkout_order->addorderHistory($orderId, $orderStatusId, '审核通过');
                        /* @todo@ 待优化，addorderHistory 方法进行了很多操作，需要完整梳理订单状态后优化 */
                        $message = '订单出库完成，合计已出库比例'.$canSORate.'%。';
                        //$message = $this->language->get('text_success');
                    }else{
                        $message = '按照库存量，大约最多'.$canSORate.'%的货物可出货，确认出库吗？';
                    }
                    //更新订单可出库比例
                    $this->model_checkout_order->updateorderpercant($orderId, $canSORate);//更新可出库比例
                    //$orderVerifyStatus = (100 == $canSORate)?2:1;
                    //$this->model_checkout_order->updateorderverify($orderId, $orderVerifyStatus);//更新订单审核状态
                    $ret = array(
                        'status' => intval($SOInfo['isSO']),
                        'message' => $message,
                    );
                }else{
                    $ret = array(
                        'status' => 2,
                        'message' => $canVerify,
                    );
                }
            }else{
                $ret = array(
                    'status' => 2,
                    'message' => '订单号不存在。',
                );
            }
        }else{
            $ret = array(
                'status' => 2,
                'message' => $this->language->get('error_permission'),
            );
        }
        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($ret));
    }

    /*
     * 判断订单是否可以进行配货操作
     */
    protected function _canVerify($orderInfo) {
        if (intval($orderInfo['hang_status']) != 1){
            if (intval($orderInfo['order_status_id']) == 20 || intval($orderInfo['order_status_id']) == 17) {
                return true;
            }else{
                return '仅“待审核”或“部分发货”的订单允许审核配货。';
            }
        }else{
            return '挂起的订单不允许审核配货。';
        }
    }

    /*
     * 根据订单的物流中心编号，获取所有参与配货的仓库，配货顺序以返回数组顺序为准。验证仓库可用性，每个仓只参与一次配货
     * 返回格式：
     * array(
     *     whPK => type,
     * )
     * type 默认 all ，允许 special
     * all：全仓配货
     * special：特殊品配货（无锡仓的爱仕达、妙洁）初期直接返回仓库距离，便于调试。如果有第三种情况，再改成special
     */
    protected function _getWarehouseListByLogcenter($LGPKInOrder) {
        $this->load->model('api/logcenters');
        $this->load->model('api/warehouse');
        $ret = array();
        //第一顺位仓：默认物流中心对应的分仓
        $defaultWHInfo = $this->model_api_logcenters->getDefaultWarehouse($LGPKInOrder);
        if ($defaultWHInfo['status']) {
            $ret[$defaultWHInfo['warehouse_id']] = 'ALL';
        }
        //第二顺位仓：默认物流中心对应的大区总仓
        $mainWHInfo = $this->model_api_warehouse->getMainWarehouseInArea($defaultWHInfo['area_in_china']);
        if ($mainWHInfo['status']) {
            $ret[$mainWHInfo['warehouse_id']] = 'ALL';
        }
        //添加大区内含特殊品配货的仓库编号，排序、去重后加入配货仓列表
        $specialWHList = $this->model_api_warehouse->getAndSortAndUniqueSpecialWarehouseInArea($defaultWHInfo);
        foreach ($specialWHList as $specialWHPK=>$distance) {
            $ret[$specialWHPK] = $distance;
        }
        return $ret;
    }

    /*
     * 循环配货主函数
     * @param   $orderId        配货订单编号
     *          $warehouseList  参与配货的仓库列表（按顺序配货）
     *              array(
     *                  whPK => type,
     *              )
     *          $soForce        强制出库标记位（true: 保存出库单，false: 估算出库比例并返回）
     * 保存出库单以前，不锁定库存，多人同时审核订单或服务器响应速度不够快时，数据会出现异常。
     */
    protected function _inventoryCheck($orderId, $userId, $warehouseList, $soForce) {
        $ret['isSO'] = false;
        $this->load->model('checkout/order');
        $this->load->model('checkout/stock_out');
        $productList = $this->model_checkout_order->getOPList($orderId);//汇总所有商品信息
        $soInfo = $this->model_checkout_stock_out->getValidSOPList($orderId);//汇总所有正常状态的出库单商品和总价
        $ret['soTotalPrice'] = floatval($soInfo['soTotalPrice']);//出库单商品汇总价格（不含优惠，用于统计可出库比例）
        /* @todo@ 待优化，在确定了 lack_quantity 列的准确性以后，不在获取出库单信息，直接取 lack_quantity 进行配货 */
        //根据商品订购数量和现有出库单数量，核算出还需要出库的数量
        $qtyToSO = array();
        $totalToSO = 0;
        foreach ($productList as $pCode=>$v) {
            foreach ($v as $opgPK=>$info) {
                $temp = $info['qty']-intval($soInfo['sopList'][$pCode][$opgPK]['qty']);
                if ($temp > 0) {
                    $qtyToSO[$pCode][$opgPK] = array(
                        'price' => $info['price'],
                        'pay_price' => $info['pay_price'],
                        'qty' => $temp,
                        'seq' => $info['seq'],
                    );
                    $totalToSO += $temp*$info['price'];
                }
            }
        }
        //单品排序 @20171218 便于配货和验货
        $qtyToSO = $this->model_checkout_order->reSortQtyToSO($qtyToSO);
        //循环模拟配货
        $this->load->model('api/inventory');
        $inventoryCanSO = array();
        $totalInAllSO = 0;
        foreach ($warehouseList as $whId=>$type) {
            //获取系统内库存清单
            $inventoryList = $this->model_api_inventory->getIL($whId, $type);
            foreach ($qtyToSO as $pCode=>$v) {
                foreach ($v as $opgPK=>$info) {
                    if ($info['qty'] && array_key_exists($pCode, $inventoryList)) {
                        $canSO = intval(min($info['qty'], $inventoryList[$pCode]));
                        $inventoryCanSO[$whId][$pCode][$opgPK] = array(
                            'price' => $info['price'],
                            'pay_price' => $info['pay_price'],
                            'qty' => $canSO,
                            'seq' => $info['seq'],
                        );
                        $qtyToSO[$pCode][$opgPK]['qty'] -= $canSO;
                        $totalInAllSO += $canSO*$info['price'];
                        $ret['soTotalPrice'] += $canSO*$info['price'];
                        //移除未配货清单中，数量为0的单品
                        if ($qtyToSO[$pCode][$opgPK]['qty'] < 1) {
                            unset($qtyToSO[$pCode][$opgPK]);
                        }
                    }
                }
                //移除未配货清单中，数量为0的单品
                if (count($qtyToSO[$pCode]) < 1) {
                    unset($qtyToSO[$pCode]);
                }
            }
        }
        //移除未配货清单中，数量为0的单品
        if (count($qtyToSO) < 1) {
            $qtyToSO = array();
        }
        $ret['qtyToSO'] = $qtyToSO;
        //保存出库单
        //if ($soForce || ($totalInAllSO >= $totalToSO)) {
        if ($soForce || 0 == count($qtyToSO)) {
            $now = date('Y-m-d H:i:s');//确保同批次的出库单创建时间一致
            $ret['isSO'] = true;
            //获取出库单批次信息
            $SOCount = $this->model_checkout_stock_out->getSOCountByOrder($orderId);
            $maxSOCount = $SOCount+count($inventoryCanSO);
            $minSOCount = $SOCount+1;
            $nowSOCount = $minSOCount;
            foreach ($inventoryCanSO as $whId=>$v) {
                $saleMoneyTemp = 0;
                $paySaleMoneyTemp = 0;
                $soData = array(
                    'refer_id' => $orderId,
                    'refer_type_id' => '1',
                    'warehouse_id' => $whId,
                    'user_id' => $userId,
                    'sale_money' => '0',
                    'pay_sale_money' => '0',
                    'status' => '0',
                    'comment' => '本批次出库单'.$nowSOCount.'('.$minSOCount.'-'.$maxSOCount.')'.' 未出库单品'.count($qtyToSO).'种',
                    'date_added' => $now,
                );
                $outId = $this->model_checkout_stock_out->add($soData);//先把位置占了，SOD信息录入后，更新状态和总价
                foreach ($v as $pCode=>$vv) {
                    foreach ($vv as $opgPK=>$info) {
                        $sodData = array(
                            'out_id' => $outId,
                            'product_code' => $pCode,
                            'product_quantity' => $info['qty'],
                            'product_price' => $info['price'],
                            'pay_product_price' => $info['pay_price'],
                            'products_money' => $info['qty']*$info['price'],
                            'pay_products_money' => $info['qty']*$info['pay_price'],
                            'counter_id' => $opgPK,
                            'order_ids' => $info['seq'],
                        );
                        if ($this->model_checkout_stock_out->addetail($sodData)) {
                            $saleMoneyTemp += $info['qty']*$info['price'];
                            $paySaleMoneyTemp += $info['qty']*$info['price'];
                            //扣减后台库存并保存操作日志
                            $this->model_api_inventory->reduceQtyForSO($whId, $pCode, $info['qty'], $outId, $userId);
                        }
                    }
                }
                $soData = array(
                    'sale_money' => $saleMoneyTemp,
                    'pay_sale_money' => $paySaleMoneyTemp,
                    'status' => 1,
                );
                $nowSOCount++;
                $this->model_checkout_stock_out->updateByPK($outId, $soData);//更新状态和总价
            }
            //所有出库单创建完成后，更新订单未发货数量
            $soInfo = $this->model_checkout_stock_out->getValidSOPList($orderId);//汇总所有正常状态的出库单商品和总价
            $this->model_checkout_order->updateLackQuantity($orderId, $soInfo['sopList']);
        }
        return $ret;
    }
    /* 订单审核配货v2 结束 */

    //订单审核配货
    public function verify() {
        $this->load->language('api/order');
        $json = array();
        if (!isset($this->session->data['api_id'])) {
            $json['error'] = $this->language->get('error_permission');
        } else {
            $this->load->model('checkout/order');
            $this->load->model('checkout/stock_out');
            if (isset($this->request->get['order_id'])) {
                $order_id = $this->request->get['order_id'];
            } else {
                $order_id = 0;
            }
            if($this->request->get['how'] == 'anyway') {
                $anyway = true;
            }else{
                $anyway = false;
            }
            $order_info = $this->model_checkout_order->getOrder($order_id);
            if(intval($order_info['hang_status']) != 1 && (intval($order_info['order_status_id']) == 20 || intval($order_info['order_status_id']) == 17)){
                $data = $this->model_checkout_order->getstockoutfromorder($order_id);//尝试多仓配货
                $this->model_checkout_order->resetRates($order_id, 'stock_out');//更新配货比例
                //$this->model_checkout_order->resetRates($order_id, 'delivery');//更新配送比例
                $this->load->model('checkout/stock_out');
                $result = $this->model_checkout_stock_out->stockoutfromorder($order_id,$data,$this->request->get['user_id'],$anyway);//保存出库单
                //创建出库单成功后，读取订单优惠信息，更新到出库单中，并更新出库单销售总价 sale_money
                if (true === $result) {
                    $OTList = $this->model_checkout_order->getOTLtZero($order_id);
                    foreach ($OTList as $OTInfo) {
                        $this->model_checkout_stock_out->insertOTIntoSO($order_id, $OTInfo['order_total_id'], $OTInfo['value']);
                    }
                }
                if ($anyway) {
                    $this->model_checkout_order->resetSORate($order_id);//更新订单出库满足率
                }
                if ($data['status'] == 'true') {
                    $this->model_checkout_order->addorderHistory($order_id,2,'审核通过');
                    $this->model_checkout_order->updateorderverify($order_id,2);
                    $this->model_checkout_order->updateorderpercant($order_id,100);
                    $json['success'] = $this->language->get('text_success');
                } elseif($data['status'] == 'false') {
                    if(!$anyway){//不出库，仅反馈可出库比例（已出库单摊销总价计算比例）
                        $total_stock_money = 0;
                        foreach($data['array_part_stock']['products'] as $val){
                            $total_stock_money += $val['pay_products_money'];
                        }
                        foreach($data['array_main_stock']['products'] as $val){
                            $total_stock_money += $val['pay_products_money'];
                        }
                        foreach($data['array_wuxi_stock']['products'] as $val){
                            $total_stock_money += $val['pay_products_money'];
                        }
                        $sum_stock_money = $this->model_checkout_stock_out->getSumStockOutPrice($order_id);
                        $total_percant = intval(($total_stock_money+$sum_stock_money)/$order_info['total']*100);
                        $total_percant = $total_percant>=100?99:$total_percant;
                        $this->model_checkout_order->updateorderpercant($order_id,$total_percant);
                        $json['message'] = '按照库存量，大约最多'.$total_percant.'%的货物可出货，确认出库吗？';
                    }else{
                        $this->model_checkout_order->updateorderverify($order_id,1);
                        $json['error'] = '可出库货物均已出库';
                    }
                } elseif($data['status'] == 'noid'){
                    $json['error'] = '找不到订单';
                }
            }else
                $json['error'] = '非法操作';
        }

        if (isset($this->request->server['HTTP_ORIGIN'])) {
            $this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
            $this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
            $this->response->addHeader('Access-Control-Max-Age: 1000');
            $this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
        }

        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }

	// public function send() {
	// 	$this->load->language('api/order');

	// 	$json = array();

	// 	if (!isset($this->session->data['api_id'])) {
	// 		$json['error'] = $this->language->get('error_permission');
	// 	} else {
	// 		$this->load->model('checkout/order');

	// 		if (isset($this->request->get['order_id'])) {
	// 			$order_id = $this->request->get['order_id'];
	// 		} else {
	// 			$order_id = 0;
	// 		}

	// 		$order_info = $this->model_checkout_order->getOrder($order_id);

	// 		if ($order_info) {
	// 			$this->model_checkout_order->addorderHistory($order_id,3,'确认开始配送');

	// 			$json['success'] = $this->language->get('text_success');
	// 		} else {
	// 			$json['error'] = $this->language->get('error_not_found');
	// 		}
	// 	}

	// 	if (isset($this->request->server['HTTP_ORIGIN'])) {
	// 		$this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
	// 		$this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
	// 		$this->response->addHeader('Access-Control-Max-Age: 1000');
	// 		$this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
	// 	}

	// 	$this->response->addHeader('Content-Type: application/json');
	// 	$this->response->setOutput(json_encode($json));
	// }

	// public function complete() {
	// 	$this->load->language('api/order');

	// 	$json = array();

	// 	if (!isset($this->session->data['api_id'])) {
	// 		$json['error'] = $this->language->get('error_permission');
	// 	} else {
	// 		$this->load->model('checkout/order');

	// 		if (isset($this->request->get['order_id'])) {
	// 			$order_id = $this->request->get['order_id'];
	// 		} else {
	// 			$order_id = 0;
	// 		}

	// 		$order_info = $this->model_checkout_order->getOrder($order_id);

	// 		if ($order_info) {
	// 			$this->model_checkout_order->addorderHistory($order_id,5,'已完成签收');

	// 			$json['success'] = $this->language->get('text_success');
	// 		} else {
	// 			$json['error'] = $this->language->get('error_not_found');
	// 		}
	// 	}

	// 	if (isset($this->request->server['HTTP_ORIGIN'])) {
	// 		$this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
	// 		$this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
	// 		$this->response->addHeader('Access-Control-Max-Age: 1000');
	// 		$this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
	// 	}

	// 	$this->response->addHeader('Content-Type: application/json');
	// 	$this->response->setOutput(json_encode($json));
	// }

	public function hang(){
		$this->load->language('api/order');

		$json = array();

		if (!isset($this->session->data['api_id'])) {
			$json['error'] = $this->language->get('error_permission');
		} else {

			$this->load->model('checkout/order');

			if (isset($this->request->get['order_id'])) {
				$order_id = $this->request->get['order_id'];
			} else {
				$order_id = 0;
			}

			$order_info = $this->model_checkout_order->getOrder($order_id);

			if($order_info){
				if(intval($order_info['order_status_id']) == 20){
					$this->model_checkout_order->updateorderhang($order_id);
					$json['success'] = $this->language->get('text_success');
				}else{
					$json['error'] = '条件不符';
				}
			}else{
				$json['error'] = $this->language->get('error_not_found');
			}
		}

		if (isset($this->request->server['HTTP_ORIGIN'])) {
			$this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
			$this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
			$this->response->addHeader('Access-Control-Max-Age: 1000');
			$this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

	public function cancelhang(){
		$this->load->language('api/order');

		$json = array();

		if (!isset($this->session->data['api_id'])) {
			$json['error'] = $this->language->get('error_permission');
		} else {

			$this->load->model('checkout/order');

			if (isset($this->request->get['order_id'])) {
				$order_id = $this->request->get['order_id'];
			} else {
				$order_id = 0;
			}

			$order_info = $this->model_checkout_order->getOrder($order_id);

			if($order_info){
				if(intval($order_info['order_status_id']) == 20){
					$this->model_checkout_order->cancelorderhang($order_id);
					$json['success'] = $this->language->get('text_success');
				}else{
					$json['error'] = '条件不符';
				}
			}else{
				$json['error'] = $this->language->get('error_not_found');
			}
		}

		if (isset($this->request->server['HTTP_ORIGIN'])) {
			$this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
			$this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
			$this->response->addHeader('Access-Control-Max-Age: 1000');
			$this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

	public function UpdateAllMultiVendorOrderStatus($order_id, $order_status_id) {
		$this->db->query("UPDATE `" . DB_PREFIX . "order_status_vendor_update` SET order_status_id = '" . (int)$order_status_id . "' WHERE order_id = '" . $order_id . "'");
		$this->db->query("UPDATE `" . DB_PREFIX . "order_product` SET order_status_id = '" . (int)$order_status_id . "' WHERE order_id = '" . $order_id . "'");
	}

	public function history() {
		$this->load->language('api/order');

		$json = array();

		if (!isset($this->session->data['api_id'])) {
			$json['error'] = $this->language->get('error_permission');
		} else {
			// Add keys for missing post vars
			$keys = array(
				'order_status_id',
				'notify',
				'sent_comment_to_all',
				'append',
				'comment'
			);

			foreach ($keys as $key) {
				if (!isset($this->request->post[$key])) {
					$this->request->post[$key] = '';
				}
			}

			$this->load->model('checkout/order');

			if (isset($this->request->get['order_id'])) {
				$order_id = $this->request->get['order_id'];
			} else {
				$order_id = 0;
			}

			$order_info = $this->model_checkout_order->getOrder($order_id);

			if ($order_info) {
				$this->model_checkout_order->addOrderHistory($order_id, $this->request->post['order_status_id'], $this->request->post['comment'], $this->request->post['notify'], $this->request->post['override'], $this->request->post['sent_comment_to_all']);
				$this->UpdateAllMultiVendorOrderStatus($order_id, $this->request->post['order_status_id']);

				$json['success'] = $this->language->get('text_success');
			} else {
				$json['error'] = $this->language->get('error_not_found');
			}
		}

		if (isset($this->request->server['HTTP_ORIGIN'])) {
			$this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
			$this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
			$this->response->addHeader('Access-Control-Max-Age: 1000');
			$this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

	public function confirmPay(){
		$this->load->model('checkout/order');
		$order_id = I('get.order_id','0');
		$order_info = $this->model_checkout_order->getOrder($order_id);
		$order_status_id = $order_info['order_status_id'];
		$user_id = I('get.user_id','0');
		$user_name = I('get.user_name');

        if(!$order_info){
			$json['error'] = '订单号不正确';
		}else{
			$this->model_checkout_order->confirmPay($order_id);
			$res = $this->model_checkout_order->getOrderById($order_id);
			if ($res) {
				$res2 = $this->model_checkout_order->getMoneyById($order_id);
				if ($res2) {
					$this->model_checkout_order->updatemoney($res,$order_id);
				}
				
			}
    		
			$comment = '确认付款成功，操作人：'.$user_name.'（'.$user_id.')';
			$this->model_checkout_order->addOrderHistory($order_id,$order_status_id,$comment);
			$json['success'] = '确认付款成功';
		}
		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));

	}

    //自动审核，暂时废弃
	public function autoverify(){
        return false;
		
		$this->load->model('checkout/order');

		$this->load->model('checkout/stock_out');

		$order_id_arr = $this->model_checkout_order->getautoverorder();

		$process_id_arr = array();

		foreach($order_id_arr as $val){
			$process_id_arr[] = $val['order_id'];
		}

		$process_id_str = implode(',',$process_id_arr);

		$log_id = $this->model_checkout_stock_out->addautolog(array('process_id'=>$process_id_str));

		foreach($order_id_arr as $val){
			$data = array();

			$data = $this->model_checkout_order->getstockoutfromorder($val['order_id']);
			
			$result = $this->model_checkout_stock_out->stockoutfromorder($val['order_id'],$data,$this->request->get['user_id']);

			if ($data['status'] == 'true') {

				$this->model_checkout_order->addorderHistory($val['order_id'],2,'审核通过');
				$this->model_checkout_order->updateorderverify($val['order_id'],2);
				$this->model_checkout_order->updateorderpercant($val['order_id'],100);

			}elseif($data['status'] == 'false') {

				$total_stock_money = 0;

				foreach($data['array_part_stock']['products'] as $val2){

					$total_stock_money += $val2['products_money'];

				}

				foreach($data['array_main_stock']['products'] as $val2){

					$total_stock_money += $val2['products_money'];

				}

				foreach($data['array_wuxi_stock']['products'] as $val2){

					$total_stock_money += $val2['products_money'];

				}

				$sum_stock_money = $this->model_checkout_stock_out->getSumStockOutPrice($val['order_id']);

				$total_percant = intval(($total_stock_money+$sum_stock_money)/$order_info['total']*100);

				$total_percant = $total_percant>=100?99:$total_percant;

				$this->model_checkout_order->updateorderpercant($val['order_id'],$total_percant);
				
			}
		}

		$this->model_checkout_stock_out->updateautolog(array(),$log_id);

		echo 'success';
		
	}

    //批量审核
    public function verifyall(){
        $this->load->model('checkout/order');
        $this->load->model('checkout/stock_out');
        $order_id_str = $this->request->get['order_id_str'];
        $order_id_arr = explode(',',$order_id_str);
        $complete_order_id_arr = array();
        foreach($order_id_arr as $val){
            $order_info = $this->model_checkout_order->getOrder($val);
            //if($order_info['order_status_id'] == 20 && intval($order_info['hang_status']) != 1){
            if(intval($order_info['hang_status']) != 1 && (intval($order_info['order_status_id']) == 20 || intval($order_info['order_status_id']) == 17)){
                $data = array();
                $data = $this->model_checkout_order->getstockoutfromorder($val);
                $result = $this->model_checkout_stock_out->stockoutfromorder($val,$data,$this->request->get['user_id']);
                $this->model_checkout_order->resetSORate($val);//更新订单出库满足率
                if ($data['status'] == 'true') {
                    $this->model_checkout_order->addorderHistory($val,2,'审核通过');
                    $this->model_checkout_order->updateorderverify($val,2);
                    $this->model_checkout_order->updateorderpercant($val,100);
                    $complete_order_id_arr[] = $val;
                }elseif($data['status'] == 'false') {
                    $total_stock_money = 0;
                    foreach($data['array_part_stock']['products'] as $val2){
                        $total_stock_money += $val2['pay_products_money'];
                    }
                    foreach($data['array_main_stock']['products'] as $val2){
                        $total_stock_money += $val2['pay_products_money'];
                    }   
                    foreach($data['array_wuxi_stock']['products'] as $val2){
                        $total_stock_money += $val2['pay_products_money'];
                    }
                    $sum_stock_money = $this->model_checkout_stock_out->getSumStockOutPrice($val);
                    $total_percant = intval(($total_stock_money+$sum_stock_money)/$order_info['total']*100);
                    $total_percant = $total_percant>=100?99:$total_percant;
                    $this->model_checkout_order->updateorderpercant($val,$total_percant);
                }
            }
        }
        if(!empty($complete_order_id_arr)){
            $json['success'] = implode(',',$complete_order_id_arr).' 订单完成审核并出库';
        }else{
            $json['success'] = '无订单通过审核';
        }
        if (isset($this->request->server['HTTP_ORIGIN'])) {
            $this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
            $this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
            $this->response->addHeader('Access-Control-Max-Age: 1000');
            $this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
        }
        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }

    /* 结束配货 */
    public function endeliver(){
        $_MAXREFUNDRATE = 0.1;//10%
        $this->load->model('checkout/order');
        $this->load->model('checkout/stock_out');
        //$this->load->model('blance/rechange');
        $order_id = $this->request->get['order_id'];
        $confirm = $this->request->get['confirm'];//0.计算差额，二次验证；1.强制退款并结束配货
        $user_id = 0;
        if(intval($confirm)){
            $user_id = $this->request->get['user_id'];
        }
        $info_pool = $this->model_checkout_order->getOrderInfoByReturnFund($order_id);
        $complete_mark = true;
        $deliver_mark = true;
        $status_arr = $this->model_checkout_stock_out->getAllActiveStockStatusByReferid($order_id);
        foreach($status_arr as $val){
            if($val['status'] != 4){
                $complete_mark = false;
            }
            if($val['status'] != 3 && $val['status'] != 4){
                $deliver_mark = false;
            }
        }

        if($info_pool['order_status_id'] == 2 || $info_pool['order_status_id'] == 17 || $info_pool['order_status_id'] == 20){
            if($info_pool['payment_code'] == 'cod'){
                if(!intval($confirm)){
                    $json['success'] = '确定吗？';
                }else{
                    if($complete_mark){
                        $this->model_checkout_order->addOrderHistory($order_id,5,'结束配货');
                    }else{
                        if($deliver_mark){
                            $this->model_checkout_order->addOrderHistory($order_id,3,'结束配货');
                        }else{
                            $this->model_checkout_order->addOrderHistory($order_id,18,'结束配货');
                        }
                    }
                    $json['success'] = 'success';

                }
            }else{//重写业务逻辑，直接从支付接口完成退款
                $return_money = $this->model_checkout_order->getReturnMoney($order_id);//获取差额
                $lackInfo = $this->model_checkout_order->getLackInfo($order_id);//获取缺货信息
                if (!intval($info_pool['isreturn'])){
                    if(intval($confirm)){//确认退款
                        if ($return_money) {
                            $paymentInfo = $this->model_checkout_order->getPaymentInfo($order_id);//获取支付信息
                            if ($paymentInfo['yijipay_tradeNo']) {
                                if ($return_money < ($info_pool['total']*$_MAXREFUNDRATE+0.01)) {
                                    if ($this->_refundOrder($order_id, $return_money, $paymentInfo['yijipay_tradeNo'], $lackInfo)) {//支付接口返回成功
                                        $message =  '结束配货，易极付正在处理退款申请。退款金额：'.$return_money;
                                    }else{//支付接口返回失败
                                        $this->model_checkout_order->saveReturnMoneyIntoOrder($order_id, $return_money);
                                        $message = '结束配货，退款失败。待退款金额：'.$return_money;
                                    }
                                }else{//退款超过预设退款比例上线
                                    $this->model_checkout_order->saveReturnMoneyIntoOrder($order_id, $return_money);
                                    $message = '结束配货。待退款金额：'.$return_money.'，超过退款比例上限 '.$_MAXREFUNDRATE.'。'."\r\n".'请联系财务进行退款操作。';
                                }
                            }else{//没有找到付款流水号
                                $this->model_checkout_order->saveReturnMoneyIntoOrder($order_id, $return_money);
                                $message = '结束配货，退款失败。待退款金额：'.$return_money;
                            }
                        }else{
                            $message = '结束配货，不需要退款。';
                        }
                        $newStatus = '18';
                        if ($complete_mark){
                            $newStatus = '5';
                        }else if ($deliver_mark) {
                            $newStatus = '3';
                        }
                        $this->model_checkout_order->addOrderHistory($order_id, $newStatus,  '结束配货，请财务人工完成退款操作。待退款金额：'.$return_money, false, false, $additionarr);
                        $this->model_checkout_order->changeordereturn($order_id);
                        $json['success'] = $message;
                    }else{//反馈提示信息，二次确认
                        $json['success'] = "建议在所有出库单完成出库后进行结束配货操作！\r\n\r\n";
                        if ($return_money) {
                            $json['success'] .= '一共'.$return_money.'元需要退还给客户，确定吗？'."\r\n".implode("\r\n", $lackInfo);
                        }else{
                            $json['success'] .= '是否结束配货？';
                        }
                    }
                }
            }
        }else{
            $json['error'] = '不符合操作条件';
        }

        if (isset($this->request->server['HTTP_ORIGIN'])) {
            $this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
            $this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
            $this->response->addHeader('Access-Control-Max-Age: 1000');
            $this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
        }

        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }

    /*
     * 发起支付接口在线退款申请
     */
    protected function _refundOrder($orderId, $returnMoney, $tradeNo, $lackInfo) {
        return false;//关闭结束配货的退款功能
        $this->load->helper('yijiSignHelper');
        $this->load->helper('dto/fastPayTradeRefund');
        $this->load->helper('YijipayClient');

        //创建退款记录
        $this->load->model('checkout/order');
        $orderOnlineRefundData = array(
            'order_id' => $orderId,
            'refund_amount' => $returnMoney,
            'comment' => implode("\r\n", $lackInfo),
            'status' => '1',
            'date_added' => date('Y-m-d H:i:s'),
        );
        $OORPK = $this->model_checkout_order->addOrderOnlineRefund($orderOnlineRefundData);
        //创建退款记录

        $objReq = new fastPayTradeRefund();
        //请求公共部分
        $objReq->setNotifyUrl('http://m.bhz360.com/index.php?route=payment/yiji_refund_v2');//自定义异步回调，记录完整支付日志
        $objReq->setPartnerId($config['partnerId']);
        $YJFPK = 'BHZ2017OOR'.substr(time(), -10).$OORPK;//基于退款表PK的流水号
        $objReq->setOrderNo($YJFPK);
        $objReq->setMerchOrderNo($YJFPK);
        $objReq->setSignType("MD5");
        //构建交易参数
        $objReq->settradeNo($tradeNo);
        $objReq->setrefundAmount($returnMoney);
        $objReq->setrefundReason('缺货退款');
        //构建请求
        $config = $this->_getConfig();
        $client = new YijiPayClient($config);
        $response = $client->execute($objReq);
        $params = json_decode($response, true);

        $ret = false;
        $status = 3;
        if($client->verify($params)){
            if($params['success']){
                if('EXECUTE_SUCCESS' == $params['resultCode'] || 'EXECUTE_PROCESSING' == $params['resultCode']) {
                    $status = 2;
                }else{
                    $status = 1;
                }
                $ret = true;
                //调用短信接口发送退款通知短信
                $this->_sendSmsForRefundOrder($orderId, $returnMoney);
            }
        }
        //更新退款记录的同步返回信息
        $orderOnlineRefundData = array(
            'status' => $status,
            'return_params' => $response,
        );
        $this->model_checkout_order->updateOrderOnlineRefund($OORPK, $orderOnlineRefundData);
        //更新退款记录的同步返回信息
        return $ret;
    }

    private function _getConfig(){
        return array(
            'partnerId' => '20161201020011981315', //商户ID
            'md5Key' => 'db3d0a81a79b6832c439bbf5ec92b77c', //商户Key
            'gatewayUrl' => "https://api.yiji.com/gateway.html" //生产环境网关
        );
    }

    /*
     * 发送通知短信
     */
    protected function _sendSmsForRefundOrder($orderId, $returnMoney) {
        $this->load->model('checkout/order');
        $this->load->model('tool/sms_log');
        $info = $this->model_checkout_order->getCAndUInfo($orderId);

        $this->load->helper('sms');
        $sms = new smsHelper();
        $appId = $this->config->get('tianyi_appid');
        $appSecret = $this->config->get('tianyi_appsecret');
        $templateId = '91553440';//缺货退款模块，详见 http://open.189.cn/ 
        //$phone = '';
        $tempParam = array(
            'user' => $info['CName'],
            'orderId' => $orderId,
            'amount' => $returnMoney,
        );
        $retC = $sms->sendSms($appId, $appSecret, $templateId, $info['CTel'], $tempParam);
        $this->model_tool_sms_log->saveData($retC['smsLog']);
        $retU = $sms->sendSms($appId, $appSecret, $templateId, $info['UTel'], $tempParam);
        $this->model_tool_sms_log->saveData($retU['smsLog']);
        $caiwuTel = '13564536028';//财务顾俊的电话号码
        $retU = $sms->sendSms($appId, $appSecret, $templateId, $caiwuTel, $tempParam);
        $this->model_tool_sms_log->saveData($retU['smsLog']);
    }

}
